package com.uranus.common.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.uranus.common.common.beans.IdPool;
import com.uranus.common.common.mapper.IdPoolMapper;
import com.uranus.common.common.service.IdPoolService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ybx
 * @since 2018-12-22
 */
@Service
public class IdPoolServiceImpl extends ServiceImpl<IdPoolMapper, IdPool> implements IdPoolService {
    @Override
    @Transactional
    public String getMaxId(String tableName, int length) {
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");
        QueryWrapper<IdPool> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("table_name",tableName).eq("create_date",dateFormat.format(new Date()));

        IdPool idPool=this.baseMapper.selectOne(queryWrapper);
        if(idPool==null || idPool.getId()==null || idPool.getId()<=0){
            idPool=new IdPool();
            idPool.setTableName(tableName);
            idPool.setCreateDate(dateFormat.format(new Date()));
            idPool.setMaxNumber(1);
            this.save(idPool);
        }else{
            idPool.setMaxNumber(idPool.getMaxNumber()+1);
            this.baseMapper.update(idPool,queryWrapper);
        }
        String id = String.format("%0"+length+"d", idPool.getMaxNumber());
        return idPool.getCreateDate()+id;
    }
}
